<template>
  <div class="pledge tabbar-iOS-height hideScrollBar" ref="scrollEl">
    <!-- 导航 -->
    <NavBar
      isFixed
      :isShowLeft="false"
      :title="$t('pledge.pageTitle')"
      :isTransparent="pageData.whiteTheme"
      :navScorllOffset="60"
      navScorllColor="#fff"
      :scrollEl="scrollEl"
      @thresholdChange="(val) => (pageData.whiteTheme = !val)"
    />
    <!-- 下拉刷新 -->
    <ClientOnly>
      <van-pull-refresh
        class="pull-refresh"
        v-model="pageData.loading"
        :pulling-text="t('mvp.other.text9')"
        :loosing-text="t('mvp.other.text10')"
        loading-text=" "
        @refresh="onRefreshRequest"
      >
        <!-- 动画 -->
        <div class="vue3Lottie items-center">
          <Vue3Lottie
            v-if="lottery.init && file.pledge"
            class="vue3Lottie-dh"
            :width="vue3LottieW"
            :height="vue3LottieH"
            :animationLink="file.pledge"
            :autoPlay="!lottery.pause"
            :pauseAnimation="!lottery.pause"
          />
          <!-- 没有质押的时候做金币动画 -->
          <img
            class="vue3Lottie-money"
            :class="{ 'vue3Lottie-money-start': lottery.pause }"
            src="/image/pledge/dh-jb-icon.svg"
          />
          <!-- 背景 -->
          <img class="vue3Lottie-bg" src="/image/pledge/dh-bg-icon.svg" />
          <!-- 绿色 icon -->
          <img class="vue3Lottie-blue1" src="/image/pledge/dh-blue-icon.svg" />
          <img
            class="vue3Lottie-green1"
            src="/image/pledge/dh-green-icon.svg"
          />
          <!-- 蓝色 icon -->
          <img class="vue3Lottie-blue2" src="/image/pledge/dh-blue-icon.svg" />
          <img
            class="vue3Lottie-green2"
            src="/image/pledge/dh-green-icon.svg"
          />
          <!-- 滚动收益 -->
          <div class="accumulated">
            <!-- 背景 -->
            <img
              class="accumulated-bg"
              src="/image/pledge/procss-bg-icon.png"
            />
            <!-- 每秒收益 -->
            <div class="accumulated-mysy">
              {{
                pageData.speed && Number(pageData.speed) > 0.000001
                  ? pageData.speed
                  : "<0.000001"
              }}/S
            </div>

            <!-- 标题 -->
            <div class="accumulated-title">{{ $t("pledge.dqjl") }}</div>

            <!-- 滚动数字 -->
            <div class="accumulated-valuebox items-center">
              <!-- 小数点之前的部分 -->
              <div class="accumulated-valuebox-prefix">{{ beforAmount }}</div>
              <!--  小数点之后的数值: accumulated.end 长度不够 6 位的场景: 不够 6 位,前面加 . 并且补 0 -->
              <div
                v-if="accumulated.end > 0 && `${accumulated.end}`.length < 6"
                class="accumulated-valuebox-suffix"
              >
                <span>.</span>
                <span v-for="(i, index) in add0" :key="index">0</span>
              </div>
              <!-- 不包含 0 的部分 -->
              <div class="accumulated-valuebox-suffix items-center">
                <!-- 需要滚动 -->
                <div
                  v-if="
                    (pageData.currentTotal == 0 && !pageData.speed) ||
                    accumulated.end == 0
                  "
                  class="accumulated-valuebox-suffix"
                  style="margin-left: -10px"
                >
                  .000000
                </div>
                <!-- 需要滚动  -->
                <CountTo
                  v-else
                  class="accumulated-valuebox-suffix"
                  :startVal="accumulated.start"
                  :endVal="accumulated.end"
                  :duration="500"
                  :decimals="0"
                  separator=""
                  :prefix="isPoint ? '.' : ''"
                />
              </div>
            </div>
          </div>
          <!-- 领取收益 -->
          <div
            class="vue3Lottie-footer"
            :class="{ 'vue3Lottie-footer-disabled': beforAmount < 1 }"
            @click.stop="
              () => {
                if (Number(beforAmount) >= 1) claimStake();
              }
            "
          >
            {{ $t("pledge.lqsyBtn") }}
          </div>
        </div>
        <!-- 说明页面 -->
        <div
          class="currentAward-left currentAward"
          @click="jumpPage('pledgeDesc')"
        >
          <img
            class="currentAward-right-img"
            src="/image/pledge/pledge-desc-icon.svg"
          />
        </div>

        <div class="content">
          <!-- 质押 + 解押 -->
          <div class="items-center content-top">
            <!-- 质押中 -->
            <div class="content-top-item items-center">
              <div class="content-top-item-title">{{ $t("pledge.zying") }}</div>
              <div class="content-top-item-value">
                {{ toThousands(decimalToLength(pageData.pledgeAmount)) }}
              </div>
              <div
                class="content-top-item-btn"
                :class="{
                  'content-top-item-btn-disabled': pageData.pledgeAmount == 0,
                }"
                @click.stop="clickPledge(false)"
              >
                {{ $t("pledge.zyingBtn") }}
              </div>
            </div>
            <!-- 可用余额 -->
            <div class="content-top-item items-center">
              <div class="content-top-item-title">{{ $t("pledge.kyye") }}</div>
              <div class="content-top-item-value">
                {{ toThousands(decimalToLength(pageData.freeAmount)) }}
              </div>
              <div
                class="content-top-item-btn"
                :class="{
                  'content-top-item-btn-disabled': pageData.freeAmount == 0,
                }"
                @click.stop="clickPledge(true)"
              >
                {{ $t("pledge.kyyeBtn") }}
              </div>
            </div>
          </div>

          <!-- 当前年化加成 -->
          <div class="dqnhjc items-center">
            <div class="dqnhjc-item items-center">
              <div
                v-if="
                  pageData.profitRate >= pageData.maxProfitRate &&
                  pageData.maxProfitRate != 0
                "
                class="items-center"
              >
                <div class="dqnhjc-item-value" style="color: #ff4040">
                  {{ decimalToLength(pageData.maxProfitRate * 100, 0, true) }}%
                </div>
                <div class="dqnhjc-item-alert">{{ $t("pledge.ydsx") }}</div>
              </div>
              <div v-else class="dqnhjc-item-value">
                {{ decimalToLength(pageData.profitRate * 100, 2, true) }}%
              </div>

              <div class="dqnhjc-item-title">{{ $t("pledge.nhsy") }}</div>
            </div>
            <img class="dqnhjc-icon" src="/image/pledge/nhsy-ts-icon.svg" />
            <div class="dqnhjc-item items-center">
              <div class="dqnhjc-item-value" style="margin-left: 2px">
                {{ decimalToLength(pageData.maxProfitRate * 100, 0, true) }}%
              </div>
              <div class="dqnhjc-item-title">
                {{ $t("pledge.nhsyText") }}
              </div>
            </div>
          </div>

          <!-- 收益+任务 -->
          <div class="box">
            <!-- 标题 -->
            <div class="items-center box-title">
              <img class="box-title-icon" src="/image/pledge/title-icon.svg" />
              <div class="box-title-text">
                {{ $t("pledge.kstsnhsy") }}
              </div>
              <img class="box-title-icon" src="/image/pledge/title-icon.svg" />
            </div>
            <!-- 累计加成 -->
            <div
              class="items-center box-cumulative"
              @click="jumpPage('detail')"
            >
              <div class="box-cumulative-text items-center">
                {{ $t("pledge.yhdjc") }}
                <span class="box-cumulative-value">
                  {{
                    decimalToLength(pageData.bonusProfitRate * 100, 2, true)
                  }}%
                </span>
              </div>
              <div class="items-center box-cumulative-right">
                <div class="box-cumulative-jl">{{ $t("pledge.zyjl") }}</div>
                <img
                  class="box-cumulative-jt"
                  src="/image/pledge/jt-right.svg"
                />
              </div>
            </div>
            <!-- 任务列表 -->
            <div class="task">
              <div
                class="task-item"
                v-for="(item, index) in taskList"
                :key="index"
                :class="{
                  'task-item-bm': taskList.length - 1 == index,
                }"
              >
                <!-- 任务类型: 2:首次充值$10, 4:充值$50, 9:充值$100, 10:充值$250, 11:充值$500, 12:充值$1000, 13:邀请5位好友注册 5:好友首充, 6:激活避险帐户并存款$10 -->
                <div class="task-item-top items-center">
                  <img
                    v-if="item.taskType == 2"
                    class="task-item-top-img"
                    src="/image/pledge/task-sc-icon.svg"
                  />
                  <img
                    v-else-if="item.taskType == 5"
                    class="task-item-top-img"
                    src="/image/pledge/task-hysc-icon.svg"
                  />
                  <img
                    v-else-if="item.taskType == 6"
                    class="task-item-top-img"
                    src="/image/pledge/task-bxzh-icon.svg"
                  />
                  <img
                    v-else-if="item.taskType == 13"
                    class="task-item-top-img"
                    src="/image/pledge/task-yyzc-icon.svg"
                  />
                  <img
                    v-else
                    class="task-item-top-img"
                    src="/image/pledge/task-cz-icon.svg"
                  />
                  <div class="task-item-top-right">
                    <div class="task-item-top-right-title">
                      {{ item.title }}
                    </div>
                    <div class="task-item-top-right-desc">
                      {{ item.taskDescription }}
                    </div>
                    <!-- 进度 -->
                    <div class="items-center" v-if="item.taskType == 13">
                      <div class="task-item-bottom-left-progress-text">
                        {{ item.finishCount }}/{{ item.totalCount }}
                      </div>
                      <van-progress
                        class="task-item-bottom-left-progress"
                        :percentage="
                          ((item.finishCount || 0) / (item.totalCount || 5)) *
                          100
                        "
                        stroke-width="6"
                        track-color="#B7DAFF"
                        color="#007BFF"
                        :show-pivot="false"
                      />
                    </div>
                  </div>
                </div>
                <!-- 进度-或者-收益 -->
                <div class="task-item-bottom items-center">
                  <div class="task-item-bottom-left items-center">
                    <!-- 收益率 -->
                    <div class="items-center">
                      <img
                        class="task-item-bottom-left-improve-img"
                        src="/image/pledge/income-icon.png"
                      />
                      <div class="task-item-bottom-left-improve">
                        +{{
                          decimalToLength(
                            new Decimal(item.taskBonusProfitRate)
                              .mul(new Decimal(100))
                              .toFixed(2)
                          )
                        }}% APY
                      </div>
                    </div>
                    <!-- BDC 奖励 -->
                    <div class="items-center" style="margin-left: 20px">
                      <img
                        class="task-item-bottom-left-improve-img"
                        src="/image/bdc.svg"
                      />
                      <div class="task-item-bottom-left-improve">
                        +{{ decimalToLength(item.prizeAmount, 0) }}
                        BDC
                      </div>
                    </div>
                  </div>
                  <!-- 跳转按钮 -->
                  <div
                    class="task-item-bottom-right"
                    @click="
                      jumpPage('pledgeRecharge', item.taskType == 6, item)
                    "
                  >
                    {{
                      item.finishCount == item.totalCount && item.taskType == 13
                        ? $t("pledge.ywc")
                        : $t("common.goText")
                    }}
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </van-pull-refresh>
    </ClientOnly>
    <!-- 质押/取消弹窗 -->
    <pledgePopup
      v-model:show="pageData.isShowPledge"
      :isPledge="pageData.isPledge"
      :detail="pageData.pledgeInfo"
      @refresh="refreshPledge"
    ></pledgePopup>
  </div>
</template>
<script setup name="pledge">
import { JUMPAPPS } from "~/config";
import { defineAsyncComponent } from "vue";
import {
  getOssFileUrl,
  debounce,
  decimalToLength,
  toThousands,
  isAndroid,
} from "@/utils";
import pledgePopup from "../../components/pledge/pledgePopup.vue";
import Decimal from "decimal.js";
import { getPledgeAccountInfo, claimStakeProfit } from "@/api/pledge";
import { navigateI18nTo } from "@/utils";
import { useGlobalStore } from "~~/store/global";
import { usePageVisibility } from "@vant/use";
import { usePageCacheStore } from "../store/modules/pageCache";
import { useUserStore } from "~~/store/modules/user";
import { useWindowSize } from "@vant/use";
import { getPayChannel } from "@/api/pay";

const CountTo = defineAsyncComponent(() =>
  import("~/components/countTo/index.vue")
);

// definePageMeta({
//   keepalive: true,
// });

const { t } = useI18n();
const globalStore = useGlobalStore();
// 如果没有登录-直接跳转登录页面
if (!globalStore.$state.token && process.client) {
  bridge.onAppLogin();
}

const userStore = useUserStore();

const scrollEl = ref();
// 资源
const file = getOssFileUrl({
  pledge: "/lottie/pledge/gold-coins-fall1.json",
});
const { width } = process.client ? useWindowSize() : { width: ref(320) };
const vue3LottieW = computed(() => {
  return (150 / 393) * width.value;
});

const vue3LottieH = computed(() => {
  return (161 / 393) * width.value;
});

// 动画
const lottery = reactive({
  pause: true,
  init: true,
});

// 由于动画无法响应式暂停播放,所以依靠 lottery.init 这个字段进行重新渲染
watch(
  () => lottery.pause,
  (newVal, oldVal) => {
    if (newVal != oldVal) {
      lottery.init = false;
      nextTick(() => {
        lottery.init = true;
      });
    }
  }
);

// firebase埋点
const firebase = useInitFirebase(); // 初始化firebase
// 页面属性
const pageData = reactive({
  whiteTheme: true,
  loading: false,
  isShowPledge: false,
  isPledge: true, // 是否点击了质押
  freeAmount: "0", // 可用余额
  pledgeAmount: "0", // 质押中金额
  profitAmount: "0", // 当前已结算收益-最多18位小数
  currentTotal: 0, // 自己计算的当前累计收益
  currentTime: "0", // 服务器当前时间
  lastSettleTime: "0", // 上次收益结算时间
  profitRate: "0", // 当前的年化收益率
  maxProfitRate: "0", // 每个等级对应过的最大收益
  baseProfitRate: "0", // VIP基础年化收益率
  bonusProfitRate: "0", // 历史总收益率加成
  speed: null, // 每秒产生的收益-最多18位小数
  pledgeInfo: {},
});

// 累计收益前一部分
const beforAmount = computed(() => {
  return decimalToLength(pageData.currentTotal, 0);
});

// 是否需要显示小数点前缀
const isPoint = computed(() => {
  if (accumulated.end > 0 && `${accumulated.end}`.length < 6) {
    return false;
  }
  return true;
});
// 要补几个 0
const add0 = computed(() => {
  const num = 6 - `${accumulated.end}`.length;
  if (num > 0) {
    return num;
  }
  return 0;
});
// 累计收益
const accumulated = reactive({
  start: 0,
  end: 0,
});

// 支付渠道: 安卓: 是不是老包,老包 120 渠道不支持,新包都支持;  iOS(只有一个包): 都可以
const isOldApp = computed(() => {
  if (isAndroid.value) {
    return !bridgeVersionCheck(JUMPAPPS().channelPay120);
  } else {
    return false;
  }
});

/**
 * @description: 获取渠道
 * 1. 从 stroe 中获取最近一次充值成功的渠道 id,添加到热门列表中
 */
let channelList = [];
const getPayChannelRequest = async () => {
  return getPayChannel({ cache: true }).then((res) => {
    // console.log("--获取渠道--", res);
    if (res) {
      // 过滤掉不符合条件的
      channelList = res?.pay?.payList.filter((e) => {
        let isok = true;
        // 1. 老包不支持 120 渠道
        if (e.payId == 120 && isOldApp.value) {
          isok = false;
        }

        return isok;
      });
    }
  });
};

// 按钮逻辑
const countInfo = ref({
  totalStakeCount: 0, // 每日质押总次数
  leftStakeCount: 0, // 剩余每日质押次数
  totalUnstakeCount: 0, // 每日取消质押总次数
  leftUnstakeCount: 0, // 剩余每日取消质押次数
});
// 根据充值档位,过滤掉不支持的档位
const arrRecharge = {
  2: 10,
  4: 50,
  9: 100,
  10: 250,
  11: 500,
  12: 1000,
  14: 10,
};
// 任务数据
const taskList = ref([]);
// 获取质押详情
let interval = null;
let isJumpOpenChat = false; // 充值页面客服字段
const pledgeAccountInfoRequest = () => {
  return getPledgeAccountInfo().then((res) => {
    if (res) {
      // 重置数组
      taskList.value = [];
      // 基本信息赋值
      isJumpOpenChat = res.assignSales == 0 && res.assignCustomer == 0;
      pageData.currentTotal = 0;
      pageData.freeAmount = res.freeAmount;
      userStore.$patch((state) => {
        state.freeAmount = res.freeAmount;
      });
      pageData.pledgeAmount = res.pledgeAmount;
      pageData.profitRate = res.profitRate;
      // pageData.profitRate = new Decimal(res.profitRate)
      //   .mul(new Decimal(100))
      //   .toFixed(2);
      pageData.baseProfitRate = res.baseProfitRate;
      pageData.bonusProfitRate = res.bonusProfitRate;
      // pageData.bonusProfitRate = new Decimal(res.bonusProfitRate)
      //   .mul(new Decimal(100))
      //   .toFixed(2);
      pageData.maxProfitRate = res.maxProfitRate;
      // pageData.maxProfitRate = new Decimal(res.maxProfitRate)
      //   .mul(new Decimal(100))
      //   .toFixed(0);
      countInfo.value = res.countInfo;

      let taskListFilter = res.taskList.filter((task) => {
        let isNotNum = 0; // 不支持的数量,所有渠道不支持才不显示
        // 2:首次充值$10, 4:充值$50, 9:充值$100, 10:充值$250, 11:充值$500, 12:充值$1000,
        const cash = arrRecharge[task.taskType];
        if (cash) {
          channelList.forEach((channel) => {
            // 2.1 如果渠道限额 小于 充值金额-禁用逻辑
            if (Number(cash) > Number(channel.rechargeMax || 9999999999)) {
              isNotNum += 1;
              console.log(
                channel.payName,
                "不支持 Max",
                task,
                "充值任务",
                channel.rechargeMax
              );
            }
            // 2.2 如果渠道最低限额 大于 充值金额 - 不显示
            else if (Number(cash) < Number(channel.rechargeMin || 0)) {
              isNotNum += 1;
              console.log(
                channel.payName,
                "不支持 Min",
                task,
                "充值任务",
                channel.rechargeMin
              );
            }
          });
        }
        console.log(task.taskType, "不支持渠道数量:", isNotNum);
        return isNotNum != channelList.length;
      });
      //  任务类型: 2:首次充值$10, 4:充值$50, 9:充值$100, 10:充值$250, 11:充值$500, 12:充值$1000, 13:邀请5位好友注册 5:好友首充, 6:激活避险帐户并存款$10
      if (taskListFilter && taskListFilter.length > 0) {
        taskListFilter.forEach((element) => {
          if (element.taskType == 2) {
            element.title = t("pledge.scczxxx").replace("xxx", "$10");
            element.taskDescription = `${t("pledge.scczxxx").replace(
              "xxx",
              "$10"
            )},${t("pledge.nhsy")} +${new Decimal(
              element.taskBonusProfitRate || 0
            ).mul(100)}%, +${element.prizeAmount} BDC`;
          } else if (element.taskType == 4) {
            element.title = `${t("pledge.rechargeTitle")} $50`;
            element.taskDescription = `${element.title} ,${t(
              "pledge.nhsy"
            )} +${new Decimal(element.taskBonusProfitRate || 0).mul(100)}%, +${
              element.prizeAmount
            } BDC`;
          } else if (element.taskType == 9) {
            element.title = `${t("pledge.rechargeTitle")} $100`;
            element.taskDescription = `${element.title} ,${t(
              "pledge.nhsy"
            )} +${new Decimal(element.taskBonusProfitRate || 0).mul(100)}%, +${
              element.prizeAmount
            } BDC`;
          } else if (element.taskType == 10) {
            element.title = `${t("pledge.rechargeTitle")} $250`;
            element.taskDescription = `${element.title} ,${t(
              "pledge.nhsy"
            )} +${new Decimal(element.taskBonusProfitRate || 0).mul(100)}%, +${
              element.prizeAmount
            } BDC`;
          } else if (element.taskType == 11) {
            element.title = `${t("pledge.rechargeTitle")} $500`;
            element.taskDescription = `${element.title} ,${t(
              "pledge.nhsy"
            )} +${new Decimal(element.taskBonusProfitRate || 0).mul(100)}%, +${
              element.prizeAmount
            } BDC`;
          } else if (element.taskType == 12) {
            element.title = `${t("pledge.rechargeTitle")} $1000`;
            element.taskDescription = `${element.title} ,${t(
              "pledge.nhsy"
            )} +${new Decimal(element.taskBonusProfitRate || 0).mul(100)}%, +${
              element.prizeAmount
            } BDC`;
          } else if (element.taskType == 14) {
            element.title = `${t("pledge.rechargeTitle")} $10`;
            element.taskDescription = `${element.title} ,${t(
              "pledge.nhsy"
            )} +${new Decimal(element.taskBonusProfitRate || 0).mul(100)}%, +${
              element.prizeAmount
            } BDC`;
          } else if (element.taskType == 13) {
            element.title = `${t("lotteryMoney.yqxwhyzc").replace("xxx", 1)}`;
            element.taskDescription = `${t("lotteryMoney.yqxwhyzc").replace(
              "xxx",
              1
            )},${t("pledge.nhsy")} +${new Decimal(
              element.taskBonusProfitRate || 0
            ).mul(100)}%, +${element.prizeAmount} BDC`;
          } else if (element.taskType == 5) {
            element.title = t("lotteryMoney.hysc");
            element.taskDescription = `${element.title} ,${t(
              "pledge.nhsy"
            )} +${new Decimal(element.taskBonusProfitRate || 0).mul(100)}%, +${
              element.prizeAmount
            } BDC`;
          } else if (element.taskType == 6) {
            element.title = t("pledge.jhbxzhbck");
            element.taskDescription = `${element.title} ,${t(
              "pledge.nhsy"
            )} +${new Decimal(element.taskBonusProfitRate || 0).mul(100)}%, +${
              element.prizeAmount
            } BDC`;
          }
          taskList.value.push(element);
        });
      }

      // res.profitAmount = 0;
      // 服务器时间校准
      let spect = res.currentTime - res.lastSettleTime; // 间隔毫秒
      // 如果很小
      if (spect < 1000) spect = 0;
      // console.warn(
      //   res.currentTime,
      //   "===",
      //   res.lastSettleTime,
      //   "间隔了",
      //   spect / 1000,
      //   "秒"
      // );
      // // 计算目前的累计的收益
      // console.warn(
      //   "服务器已结算收益:",
      //   res.profitAmount,
      //   "--每秒增加--",
      //   res.secondProfitAmount
      // );
      // res.profitAmount = '0.040018452063629395'
      // res.secondProfitAmount = '0.000012489630898021'
      // Math.floor 向下取整,相当于是比服务慢了一秒
      pageData.currentTotal = new Decimal(res.secondProfitAmount)
        .mul(new Decimal(Math.floor(spect / 1000)))
        .add(new Decimal(res.profitAmount))
        .toFixed(6);

      // console.warn("自己计算的到的初始值:", pageData.currentTotal);
      // 界面显示值
      pageData.speed = decimalToLength(res.secondProfitAmount, 6); // 速率
      lottery.pause = Number(res.secondProfitAmount) == 0;
      if (!`${pageData.currentTotal}`.includes(".")) {
        pageData.currentTotal = `${pageData.currentTotal}.00000000`;
      }

      accumulated.start =
        decimalToLength(pageData.currentTotal, 6).split(".")[1] * 1;
      accumulated.end =
        decimalToLength(pageData.currentTotal, 6).split(".")[1] * 1;

      // 每秒增加收益
      if (interval) {
        clearTimeout(interval);
        interval = null;
      }
      if (res.secondProfitAmount > 0) {
        interval = setInterval(() => {
          accumulated.start =
            decimalToLength(pageData.currentTotal, 6).split(".")[1] * 1;
          pageData.currentTotal = new Decimal(pageData.currentTotal)
            .add(new Decimal(res.secondProfitAmount))
            .toFixed(18);

          // console.log("当前累计:", pageData.currentTotal);
          if (!`${pageData.currentTotal}`.includes(".")) {
            pageData.currentTotal = `${pageData.currentTotal}.00000000`;
          }
          accumulated.end =
            decimalToLength(pageData.currentTotal, 6).split(".")[1] * 1;
        }, 1000);
      }
    }
  });
};

const pageVisibility = usePageVisibility();
watch(pageVisibility, (value) => {
  console.warn("从后台进入前台: 刷新数据 ", value);
  if (value == "visible") pledgeAccountInfoRequest();
});

// 下拉刷新
const onRefreshRequest = async () => {
  try {
    // 1. 获取质押详情
    await pledgeAccountInfoRequest();
    pageData.loading = false;
  } catch (error) {
    pageData.loading = false;
  }
};

// 先获取,渠道信息,在获取质押任务数据,然后根据渠道,过滤掉不支持的档位信息
onMounted(() => {
  firebase?.logEvent("BDC_H5_Pledge_PUV");
  getPayChannelRequest().then(() => {
    // 1. 获取质押详情
    pledgeAccountInfoRequest();
  });
});

// 领取收益
const claimStake = debounce(
  () => {
    if (Number(beforAmount.value) < 1) return;
    // 1. loading
    showLoadingToast({
      message: `${t("common.requestIng")}...`,
      forbidClick: true,
      duration: 15000,
    });
    claimStakeProfit({
      amount: beforAmount.value,
    }).then((res) => {
      if (res || res == 1203) {
        // 2. 刷新页面数据
        pledgeAccountInfoRequest()
          .then(() => {
            res != 1203 && showToast(t("pledge.lqcg"));
          })
          .catch(() => {
            showToast({
              message: t("common.networkAnomaly"),
              forbidClick: true,
            });
          });
      } else {
        showToast({
          message: t("common.networkAnomaly"),
          forbidClick: true,
        });
      }
    });
  },
  2000,
  false
);

// 质押/取消质押
const clickPledge = (val) => {
  if (val && pageData.freeAmount == 0) return;
  if (!val && pageData.pledgeAmount == 0) return;
  // 非 0 账户不支持,质押
  if (val && userStore.$state.accountType != 0) {
    return showToast(t("common.zwqx"));
  }

  pageData.pledgeInfo = {
    freeAmount: pageData.freeAmount, // 可用余额
    pledgeAmount: pageData.pledgeAmount, // 质押中金额
    leftStakeCount: countInfo.value.leftStakeCount, // 剩余每日质押次数
    leftUnstakeCount: countInfo.value.leftUnstakeCount, // 取消质押次数
  };
  pageData.isPledge = val;
  pageData.isShowPledge = true;
};

// 质押结果
const refreshPledge = () => {
  // 0. 关闭定时任务,获取详情中会重新开启
  if (interval) {
    clearTimeout(interval);
    interval = null;
  }
  // 1. 关闭弹窗
  pageData.isShowPledge = false;
  // 2. 刷新页面
  pledgeAccountInfoRequest();
};

// 点击-页面跳转
const jumpPage = async (val, isApp = false, params) => {
  console.log("页面跳转:", val, isApp, params);
  firebase?.logEvent("BDC_H5_Pledge_Click_Recharge_PUV");
  if (isApp) {
    if (params.taskType == 6) {
      firebase?.logEvent("BDC_H5_Pledge_Click_HedgeAccount");
      const hedgeAccount = JUMPAPPS()["hedgeAccount"]();
      bridge.jumpAppRoute(hedgeAccount.routeKey, isAndroid.value, hedgeAccount);
    }
  } else if (params && (params.taskType == 13 || params.taskType == 5)) {
    firebase?.logEvent("BDC_H5_Pledge_Click_inviteFriends");
    navigateI18nTo({
      path: "/lottery-v3/invite-friends",
    });
  } else if (val === "pledgeRecharge") {
    if (!params) return;
    const pageCache = usePageCacheStore();
    pageCache.removeData("pledge-recharge-channel");
    navigateI18nTo({
      path: "/pledge/channel-select",
      query: {
        // payId: pageData.selectChannel ? pageData.selectChannel.payId : "",
        isJumpOpenChat: isJumpOpenChat ? 1 : 0,
        cash: arrRecharge[params.taskType],
        sourceId: params.taskType,
      },
    });
  } else if (val === "pledgeDesc") {
    navigateI18nTo({
      path: "/pledge/desc",
    });
  } else if (val === "detail") {
    navigateI18nTo({
      path: "/pledge/detail",
    });
  }
};
</script>
<style lang="scss" scoped>
.content {
  position: relative;
  width: 100vw;
  padding: 0 15 * 2px;

  &-top {
    padding: 10 * 2px 0;
    justify-content: space-evenly;
    background-color: #fff;
    border-radius: 8 * 2px;
    margin-bottom: 10 * 2px;

    &-item {
      padding: 10 * 2px 0;
      flex-direction: column;
      justify-content: center;
      width: 167 * 2px;
      border-radius: 8 * 2px;
      background: linear-gradient(180deg, #e7f2fe 0%, #fff 100%);

      &-title {
        font-size: 11 * 2px;
        color: #002853;
      }
      &-value {
        margin: 10 * 2px 0;
        font-size: 17 * 2px;
        color: #007bff;
        font-weight: 590;
      }
      &-btn {
        background-color: #007bff;
        width: calc(100% - 10 * 4px);
        height: 30 * 2px;
        line-height: 30 * 2px;
        border-radius: 4 * 2px;
        font-size: 13 * 2px;
        color: #fff;
        font-weight: 590;
        text-align: center;

        &-disabled {
          background-color: #a0ceff !important;
        }
      }
    }
  }
}

.dqnhjc {
  position: relative;
  width: 100%;
  justify-content: space-between;
  background: transparent;
  border-top-left-radius: 8 * 2px;
  border-top-right-radius: 8 * 2px;

  &-item {
    justify-content: center;
    flex-direction: column;
    padding: 6 * 2px 10 * 2px 15 * 2px 10 * 2px;
    width: calc(50% - 1px);
    border-radius: 8 * 2px 8 * 2px 0px 0px;
    background: linear-gradient(180deg, #fff 0%, #d7ebff 100%);

    &-title {
      color: #141924;
      font-size: 11 * 2px;
    }

    &-value {
      color: #007bff;
      font-size: 17 * 2px;
      font-weight: 590;
      margin-bottom: 1.5 * 2px;
    }

    &-alert {
      margin-left: 2 * 2px;
      background: linear-gradient(
        90deg,
        rgba(255, 64, 64, 0) 0%,
        rgba(255, 64, 64, 0.16) 50.14%,
        rgba(255, 64, 64, 0) 100%
      );
      padding: 1.5 * 2px 6 * 2px;
      max-width: 95 * 2px;
      color: #ff4040;
      font-size: 10 * 2px;
      font-weight: 400;
      text-align: center;
    }
  }
  &-icon {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    width: 24 * 2px;
    height: 24 * 2px;
  }
}

.accumulated {
  position: absolute;
  z-index: 9;
  bottom: 0 * 2px;
  width: calc(100% - 15 * 4px);
  height: 159 * 2px;

  &-bg {
    width: 100%;
    height: 159 * 2px;
  }

  &-mysy {
    position: absolute;
    top: 7 * 2px;
    left: 15 * 2px;
    color: #fff;
    font-size: 12 * 2px;
    font-weight: 590;
  }

  &-title {
    position: absolute;
    top: 13 * 2px;
    left: 50%;
    transform: translateX(-50%);
    color: #002853;
    font-size: 15 * 2px;
    font-weight: 590;
  }
  &-valuebox {
    justify-content: center;
    position: absolute;
    top: 44 * 2px;
    left: 10 * 2px;
    width: calc(100% - 10 * 4px);
    padding: 7 * 2px 0;
    background-color: #fff;
    border-radius: 4 * 2px;
    &-prefix {
      color: #007bff;
      font-size: 27 * 2px;
      font-weight: 700;
      letter-spacing: 17px;
    }
    &-suffix {
      align-self: flex-end;
      color: #007bff;
      font-size: 20 * 2px;
      font-weight: 700;
      letter-spacing: 17px;
    }
  }
}

.box {
  position: relative;
  top: -5 * 2px;
  background: #fff;
  border-radius: 8 * 2px;
  padding: 15 * 2px 10 * 2px;

  &-title {
    justify-content: center;
    margin-bottom: 13 * 2px;

    &-icon {
      width: 10 * 2px;
    }
    &-text {
      text-align: center;
      margin: 0 10 * 2px;
      color: #141924;
      font-size: 15 * 2px;
      font-weight: 590;
    }
  }

  &-cumulative {
    height: 30 * 2px;
    padding: 0 10 * 2px;
    border-radius: 4 * 2px;
    background: #f0f3fa;
    justify-content: space-between;
    margin-bottom: 12 * 2px;

    &-text {
      height: 30 * 2px;
      line-height: 30 * 2px;
      color: #999da7;
      font-size: 13 * 2px;
      border-radius: 8 * 2px;
    }
    &-value {
      margin-left: 10 * 2px;
      color: #007bff;
      font-weight: 590;
      font-size: 13 * 2px;
    }
    &-right {
      height: 22 * 2px;
      border-radius: 100px;
      border: 0.7px solid #007bff;
      padding: 2 * 2px 10 * 2px;
    }
    &-jl {
      margin-right: 8 * 2px;
      color: #007bff;
      font-size: 13 * 2px;
    }
  }
}

.task {
  &-item {
    padding: 10 * 2px 10 * 2px 6 * 2px 10 * 2px;
    margin-bottom: 10 * 2px;
    border: 0.7px solid rgba(115, 119, 128, 0.15);
    border-radius: 8 * 2px;
    &-bm {
      margin-bottom: 0;
    }
    &-top {
      margin-bottom: 10 * 2px;

      &-img {
        width: 40 * 2px;
        height: 40 * 2px;
        border-radius: 40 * 2px;
        margin-right: 10 * 2px;
      }
      &-right {
        flex: 1;
        &-title {
          color: #141924;
          font-size: 13 * 2px;
          font-weight: 510;
          margin-bottom: 6 * 2px;
          word-break: break-word;
        }
        &-desc {
          @include multi-line-omit(3);
          color: #999da7;
          font-size: 12 * 2px;
          letter-spacing: -0.2 * 2px;
          word-break: break-word;
          margin-bottom: 8 * 2px;
        }
      }
    }
    &-bottom {
      justify-content: space-between;
      border-top: 0.7px solid rgba(115, 119, 128, 0.15);
      padding-top: 6 * 2px;
      &-left {
        padding: 3 * 2px 10 * 2px;
        border-radius: 100px;

        &-progress {
          // margin-right: 12 * 2px;
          width: 70 * 2px;
          &-text {
            color: #007bff;
            font-size: 11 * 2px;
            font-weight: 590;
            margin-right: 4 * 2px;
          }
        }
        &-improve {
          color: #007bff;
          font-size: 11 * 2px;
          font-weight: 590;
          &-img {
            width: 14 * 2px;
            height: 14 * 2px;
            margin-right: 4 * 2px;
          }
        }
      }
      &-right {
        // min-width: 95 * 2px;
        border-radius: 8px;
        background: #007bff;
        padding: 5 * 2px 11 * 2px;
        text-align: center;
        font-size: 13 * 2px;
        color: #fff;
        font-weight: 590;
        &-disabled {
          background: #a0ceff !important;
        }
      }
    }
  }
}
.pledge {
  position: relative;
  background: linear-gradient(180deg, #007bff 0%, #f1f4fb 42.94%);
  overflow-y: scroll;
  overflow-x: hidden;
  will-change: scroll-position;
  padding-bottom: 20 * 2px;
}
.currentAward {
  position: absolute;
  top: 10 * 2px;
  left: 0;

  &-left {
    border-top-right-radius: 100px;
    border-bottom-right-radius: 100px;
    background: rgba(255, 255, 255, 0.3);
    padding: 2 * 2px 15 * 2px 2 * 2px 15 * 2px;
    &-img {
      width: 19 * 2px;
      height: 19 * 2px;
    }
  }
}

.vue3Lottie {
  position: relative;
  flex-direction: column;
  justify-content: flex-start;
  height: 295 * 2px;
  margin-bottom: 10 * 2px;

  &-dh {
    position: relative;
    z-index: 9;
    top: 0 * 2px;
  }
  &-money {
    @keyframes moneyfz {
      0% {
        top: 0px;
      }
      50% {
        top: 15px;
      }
      100% {
        top: 0px;
      }
    }
    position: absolute;
    z-index: 9;
    top: 15 * 2px;
    left: 50%;
    transform: translateX(-50%);
    width: 33 * 2px;
    height: 33 * 2px;
    display: none;
    &-start {
      display: block;
      animation: moneyfz 3s ease-in-out infinite;
    }
  }
  &-bg {
    position: absolute;
    top: -35 * 2px;
    left: 50%;
    transform: translateX(-50%);
    width: 262 * 2px;
    height: 262 * 2px;
  }

  &-blue1 {
    position: absolute;
    z-index: 1;
    top: 37 * 2px;
    left: 58 * 2px;
    width: 13 * 2px;
    height: 40 * 2px;
  }
  &-green1 {
    position: absolute;
    z-index: 1;
    top: 79 * 2px;
    left: 102 * 2px;
    width: 13 * 2px;
    height: 40 * 2px;
  }

  &-blue2 {
    position: absolute;
    z-index: 1;
    top: 39 * 2px;
    right: 41 * 2px;
    width: 13 * 2px;
    height: 40 * 2px;
  }

  &-green2 {
    position: absolute;
    z-index: 1;
    top: 94 * 2px;
    right: 86 * 2px;
    width: 13 * 2px;
    height: 40 * 2px;
  }
  &-footer {
    position: absolute;
    z-index: 9;
    bottom: 16 * 2px;
    width: 343 * 2px;
    padding: 12 * 2px 0px;
    background-color: #007bff;
    border-radius: 4 * 2px;
    color: #fff;
    font-size: 15 * 2px;
    font-weight: 590;
    text-align: center;
    &-disabled {
      background: #a0ceff !important;
    }
  }
}
</style>
<style lang="scss">
// van-loading van-loading--circular van-pull-refresh__loading
.banner {
  .van-swipe__indicator {
    left: 25% !important;
  }
}
:root:root {
  --van-pull-refresh-head-text-color: #fff;
}
.pull-refresh {
  .van-loading__text {
    color: #fff;
  }
  .van-loading--circular {
    color: #fff !important;
  }
}
</style>
